﻿using System;
using System.Configuration;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.StorageClient;

namespace AzureQueue
{
    public class AzureQueueContext
    {
        public const string EmailQueueName = "email";

        public CloudStorageAccount Account { get; private set; }
        public CloudQueueClient QueueClient { get; private set; }

        RetryPolicy GetRetryPolicy()
        {
            // Retry after one hour if fails
            return RetryPolicies.Retry(3, TimeSpan.FromSeconds(int.Parse(ConfigurationManager.AppSettings["QueueDequeueRetrySleepSeconds"])));            
        }

        /// <summary>
        /// Get settings from a hosted service configuration or .NET configuration file
        /// </summary>
        /// <param name="configurationSettingName">Name of .NET configuration file settings</param>
        /// <param name="hostedService">If true then settings from the hosted service is used</param>
        public AzureQueueContext(string configurationSettingName, bool hostedService)
        {
            if (hostedService)
            {
                CloudStorageAccount.SetConfigurationSettingPublisher(
                    (configName, configSettingPublisher) =>
                    {
                        var connectionString = RoleEnvironment.GetConfigurationSettingValue(configName);
                        configSettingPublisher(connectionString);
                    }
                );
            }
            else
            {
                CloudStorageAccount.SetConfigurationSettingPublisher(
                    (configName, configSettingPublisher) =>
                    {
                        var connectionString = ConfigurationManager.ConnectionStrings[configName].ConnectionString;
                        configSettingPublisher(connectionString);
                    }
                );
            }

            Account = CloudStorageAccount.FromConfigurationSetting(configurationSettingName);

            QueueClient = Account.CreateCloudQueueClient();
            QueueClient.RetryPolicy = GetRetryPolicy();
        }

        /// <summary>
        /// Get settings from a cloud storage account
        /// </summary>
        /// <param name="connectionString">Connection string to the cloud storage account</param>
        public AzureQueueContext(string connectionString)
        {
            Account = CloudStorageAccount.Parse(connectionString);

            QueueClient = Account.CreateCloudQueueClient();
            QueueClient.RetryPolicy = GetRetryPolicy();
        }
    }
}